
import datetime

from ...pao_python.pao.data import (DataProcess, data_to_string_date,
                                    dataframe_to_list, get_cur_time,
                                    process_db)
# from ...service.welfare_institution.accommodation_process import AccommodationProcess
from ...pao_python.pao.remote import JsonRpc2Error
from ...pao_python.pao.service.data.mongo_db import (C, F, MongoFilter,
                                                     MongoService, N, as_date)
from ...service.app.my_order import RecordStatus
from ...service.buss_mis.transaction_management import TransactionService
from ...service.buss_pub.bill_manage import (BillManageService, OperationType,
                                             Status, TypeId)
from ...service.common import (SerialNumberType, delete_data, find_data,
                               get_code, get_condition, get_current_user_id,
                               get_date_slot, get_info, get_serial_number,
                               insert_data, operation_result, update_data)
from ...service.constant import ApplyState
from ...service.mongo_bill_service import MongoBillFilter


class Order():
    '''单据对象'''

    def __init__(self, purchaser_id, service_provider_id, order_fee, detail, remark):
        '''构造函数'''
        self.purchaser_id = purchaser_id
        self.service_provider_id = service_provider_id
        self.order_fee = order_fee
        self.detail = detail
        self.remark = remark
        self.order_date = get_cur_time().strftime("%Y-%m-%d %H:%M:%S")
        self.status = 'new'

    def to_dict(self):
        return self.__dict__


class OrderRecord():
    '''订单记录对象'''

    def __init__(self, order_id, service_product_id, servicer_id, content, option_list, begin_date=None, end_date=None):
        '''构造函数'''
        # 服务订单ID
        self.order_id = order_id
        # 服务产品ID
        self.service_product_id = service_product_id
        # 开始时间
        self.start_date = begin_date
        # 服务完成时间
        self.end_date = end_date
        # 服务人员
        self.servicer_id = servicer_id
        # 服务内容
        self.content = content
        # 当前状态
        self.status = 'new'
        # 服务选项
        self.option_list = option_list
        # 计价金额(通过项目中的计价公式+订单项目的选项+服务记录的选项清单生成)
        self.valuation_amount = float(0)

    def to_dict(self):
        return self.__dict__


class Ledger():
    '''台账对象'''

    def __init__(self, user_id, service_end_date, total_amount, item_list, remark):
        '''构造函数'''
        # 用户ID
        self.user_id = user_id
        # 服务结束时间
        self.service_end_date = service_end_date
        # 总金额
        self.total_amount = total_amount
        # 服务项目列表
        self.item_list = item_list
        # 备注
        self.remark = remark

    def to_dict(self):
        return self.__dict__


class ServiceOrderCommentObject():
    '''新增/编辑服务订单评论'''

    def __init__(self, user_id, order_id, product_id, service_attitude, service_quality, opinion_remarks):
        '''构造函数'''
        # 操作人id
        self.user_id = user_id
        # 订单id
        self.order_id = order_id
        # 服务产品id
        self.product_id = product_id
        # 服务态度评分
        self.service_attitude = service_attitude
        # 服务质量评分
        self.service_quality = service_quality
        # 意见备注
        self.opinion_remarks = opinion_remarks

    def to_dict(self):
        return self.__dict__


class ServiceOperationService(MongoService):
    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        DataProcess.__init__(self, db_addr, db_port, db_name, db_user, db_pwd)
        # self.db_name = db_name
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_server = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)
        self.transaction_service = TransactionService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

        # self.accommodation_process = AccommodationProcess(
        # db_addr, db_port, db_name, inital_password, session)

    def get_service_provider_list(self, order_ids, condition, page=None, count=None):
        '''查询服务商列表'''
        if 'date_range' in condition.keys():
            condition['start_date'] = condition['date_range'][0]
            condition['end_date'] = condition['date_range'][1]
            keys = ['id', '  ', 'start_date', 'end_date', 'address',
                    'sp_ability_level', 'sp_credit_level', 'business_name']
            values = self.get_value(condition, keys)
            _filter = MongoBillFilter()
            _filter.lookup_bill('PT_User', 'service_provider_id', 'id', 'user')\
                .add_fields({'user_name': '$user.name',
                             'address': '$user.address',
                             'telephone': '$user.telephone',
                             })\
                .match_bill((C('id') == values['id'])
                            & (C('organization_id').inner(order_ids))
                            & (C('register_date') >= as_date(values['start_date']))
                            & (C('register_date') <= as_date(values['end_date']))
                            & (C('user_name').like(values['name']))
                            & (C('address').like(values['address'])))\
                .project({'_id': 0, 'user._id': 0})
            res = self.page_query(
                _filter, 'PT_Service_Provider_Register', page, count)
            return res

        if 'business_name' in condition.keys():
            keys = ['business_name']
            values = self.get_value(condition, keys)
            _filter = MongoBillFilter()
            _filter.match_bill((C('name').like(values['business_name'])) & (C('organization_info.personnel_category') == "服务商"))\
                .project({'_id': 0})
            res = self.page_query(
                _filter, 'PT_User', page, count)
            return res

        if 'admin_area_id' in condition.keys():
            keys = ['admin_area_id']
            values = self.get_value(condition, keys)
            _filter = MongoBillFilter()
            _filter.match_bill((C('admin_area_id') == values['admin_area_id']) & (C('organization_info.personnel_category') == "服务商"))\
                .project({'_id': 0})
            res = self.page_query(
                _filter, 'PT_User', page, count)
            return res
        keys = ['name']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.lookup_bill('PT_Service_Follow_Collection', 'id', 'business_id', 'flow_list')\
            .add_fields({'flow_list': self.ao.array_filter('$flow_list', 'record', (F('$record.type') == 'follow').f)})\
            .add_fields({'follow_num': self.ao.size('$flow_list')})\
            .match_bill((C('organization_info.personnel_category') == "服务商") & (C('name').like(values['name'])))\
            .project({'_id': 0, 'flow_list._id': 0})
        if 'profile' in condition.keys() and condition['profile'] == 'up':
            _filter.sort({'follow_num': -1})
        res = self.page_query(
            _filter, 'PT_User', page, count)
        return res

    def get_Subsidy_service_provider_list(self, condition, page, count):
        '''获取待审核服务商列表'''
        if 'date_range' in condition.keys():
            condition['start_date'] = condition['date_range'][0]
            condition['end_date'] = condition['date_range'][1]
        keys = ['id', 'name', 'organization_nature',
                'address', 'start_date', 'end_date']
        persion_id = get_current_user_id(self.session)
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.lookup_bill('PT_Approval_Process', 'id', 'business_id', 'process')\
               .lookup_bill('PT_User', 'service_provider_id', 'id', 'org')\
            .add_fields({'new_field': self.ao.array_filter(
                "$process", "aa", ((F('$aa.approval_user_id') == persion_id) & (F('$aa.step_no') == (F('step_no'))) & (F('$aa.status') == '待审批')).f)}).match((C("new_field") != None) & (C("new_field") != []))\
            .match_bill((C('register_date') >= as_date(values['start_date']))
                        & (C('register_date') <= as_date(values['end_date']))
                        & (C('id') == values['id'])
                        & (C('org.name').like(values['name']))
                        & (C('organization_nature').like(values['organization_nature']))
                        & (C('address').like(values['address'])))\
            .project({'_id': 0, 'new_field._id': 0, 'process._id': 0, 'org._id': 0})
        res = self.page_query(
            _filter, 'PT_Service_Provider_Register', page, count)
        return res

    def get_service_provider_byId(self, condition, page=None, count=None):
        '''根据id查询服务商'''
        keys = ['id']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == values['id']))\
            .project({'_id': 0})
        res = self.page_query(
            _filter, 'PT_User', page, count)
        return res

    def get_current_service_provider(self, condition, page=None, count=None):
        '''获取当前用户的供应商信息'''
        userid = get_current_user_id(self.session)
        _filter = MongoBillFilter()
        _filter.lookup_bill('PT_User', 'service_provider_id', 'id', 'user') \
            .add_fields({'user_name': '$user.name',
                         'address': '$user.address',
                         'telephone': '$user.telephone',
                         'create_date': self.ao.date_to_string('$create_date'),
                         'modify_date': self.ao.date_to_string('$modify_date')}) \
            .match_bill((C('service_provider_id') == userid)) \
            .project({'_id': 0, 'user._id': 0})
        res = self.page_query(
            _filter, "PT_Service_Provider_Register", page, count)
        return res

    def update_service_provider(self, serviceProvider):
        '''新增/修改服务商'''
        res = 'Fail'

        # data_info = get_info({**serviceProvider},self.session)
        print(serviceProvider)
        # def process_func(db):
        #     nonlocal res
        # if 'id' in serviceProvider.keys():
        #     flag = OperationType.update.value
        # else:
        #     flag = OperationType.add.value
        #     data_info['register_date'] = datetime.datetime.now()
        # if 'service_provider_id' not in data_info:
        #     data_info['service_provider_id'] = get_current_user_id(
        #         self.session)
        #     data_info['status'] = "正在申请"
        # bill_id = self.bill_manage_server.add_bill(flag,
        #                                            TypeId.serviceProvider.value, data_info, 'PT_Service_Provider_Register')
        # if bill_id:
        #     res = 'Success'
        # process_db(self.db_addr, self.db_port, self.db_name, process_func)
        # return res
        person_id = get_current_user_id(self.session)
        # 判断是否已经存在该组织机构
        _filter = MongoBillFilter()
        _filter.match_bill((C('name') == serviceProvider['name'])
                           & (C('admin_area_id') == serviceProvider['admin_area_id'])
                           & (C('organization_info.super_org_id') == serviceProvider['super_org_id'])
                           & (C('organization_info.personnel_category') == '服务商')
                           & (C('personnel_type') == '2'))\
            .project({'_id': 0})
        provider_res = self.query(_filter, 'PT_User')
        if len(provider_res) > 0:
            res = '该服务商已存在'
        else:
            # 查询是否已经存在申请记录
            _filter = MongoBillFilter()
            _filter.match_bill((C('name') == serviceProvider['name'])
                               & (C('admin_area_id') == serviceProvider['admin_area_id'])
                               & (C('super_org_id') == serviceProvider['super_org_id'])
                               & (C('organization_nature') == serviceProvider['organization_nature'])
                               & (C('step_no') != -1))\
                .project({'_id': 0})
            record_res = self.query(_filter, 'PT_Service_Provider_Register')
            if len(record_res) > 0:
                res = '已经申请过了，不可重复申请'
            else:
                data_info = get_info(serviceProvider, self.session)
                # 根据审批定义新增审核过程表数据，新增业务表数据
                _filter = MongoBillFilter()
                _filter.match_bill((C('approval_type') == 'ProviderApply'))\
                    .project({'_id': 0})
                res_define = self.query(_filter, 'PT_Approval_Define')
                if len(res_define) > 0 and len(res_define[0]['approval_list']) > 0:
                    for approval in res_define[0]['approval_list']:
                        if approval['step_no'] == 1:
                            process_data_list = []
                            # 查找属于平台的组织结构
                            _filter = MongoBillFilter()
                            _filter.match_bill((C('personnel_type') == '2') & (C('organization_info.personnel_category') == '平台'))\
                                .project({'_id': 0})
                            forumInfo = self.query(_filter, 'PT_User')
                            print(forumInfo)
                            # 拿到平台的id以及角色id确定可以审核的人id
                            _filter = MongoBillFilter()
                            _filter.match_bill((C('role_id') == approval['approval_user_id']) & (C('role_of_account_id') == forumInfo[0]['id']))\
                                .project({'_id': 0})
                            aboutUserIdList = self.query(
                                _filter, 'PT_Set_Role')
                            approval_user_id = aboutUserIdList[0]['principal_account_id']
                            process_data = {"define_id": res_define[0]['id'], "business_id": data_info['id'], "approval_user_id":
                                            approval_user_id, "step_no": approval['step_no'], "opinion": [], "status": "待审批"}
                            process_data_list.append(
                                get_info(process_data, self.session))
                            data_info['step_no'] = process_data_list[0]['step_no']
                            data_info['status'] = ApplyState.apply
                            data_info['register_date'] = get_cur_time()
                            data_info['apply_user_id'] = person_id
                            data = [data_info, process_data_list]
                            bill_id = self.bill_manage_server.add_bill(
                                OperationType.add.value, TypeId.servicePersonal.value, data, ['PT_Service_Provider_Register', 'PT_Approval_Process'])
                            if bill_id:
                                res = 'Success'
                        if approval['step_no'] == 2:
                            process_data_list = []
                            # 根据申请人的信息去user表查所属行政区划id
                            _filter = MongoBillFilter()
                            _filter.match_bill((C('id') == person_id))\
                                .project({'_id': 0})
                            userInfo = self.query(_filter, 'PT_User')
                            print("数据>>>>>>>>>>", userInfo)
                            # 根据行政区划id找出当前区划下的民政机构
                            _filter = MongoBillFilter()
                            _filter.match_bill((C('admin_area_id') == userInfo[0]['admin_area_id']) & (C('personnel_type') == '2') & (C('organization_info.personnel_category') == '民政'))\
                                .project({'_id': 0})
                            mzOrganizationInfo = self.query(_filter, 'PT_User')
                            print("这里报错吗", mzOrganizationInfo)
                            # 根据角色id以及机构id找出审核人id
                            _filter = MongoBillFilter()
                            _filter.match_bill((C('role_id') == approval['approval_user_id']) & (C('role_of_account_id') == mzOrganizationInfo[0]['id']))\
                                .project({'_id': 0})
                            aboutUserIdList = self.query(
                                _filter, 'PT_Set_Role')
                            approval_user_id = aboutUserIdList[0]['principal_account_id']
                            # print("长者33333333333333333333333333333333333333333333",approval_user_id)
                            process_data = {"define_id": res_define[0]['id'], "business_id": data_info['id'], "approval_user_id":
                                            approval_user_id, "step_no": approval['step_no'], "opinion": [], "status": "待审批"}
                            process_data_list.append(
                                get_info(process_data, self.session))
                            data = [process_data_list]
                            bill_id = self.bill_manage_server.add_bill(
                                OperationType.add.value, TypeId.servicePersonal.value, data, ['PT_Approval_Process'])
                            if bill_id:
                                res = 'Success'
        return res

    def update_service_provider_record(self, reviewed_result):
        '''# 服务商审核'''
        res = 'Fail'

        persion_id = get_current_user_id(self.session)
        print(reviewed_result)
        if 'id' in reviewed_result.keys():
            # 查询记录表的记录
            _filter = MongoBillFilter()
            _filter.match_bill((C('id') == reviewed_result['id']))\
                .project({'_id': 0})
            apply_record = self.query(_filter, 'PT_Service_Provider_Register')
            if len(apply_record) > 0:
                jlb_record = apply_record[0]
                # 查询过程表的数据
                _filter_process = MongoBillFilter()
                _filter_process.match_bill((C('business_id') == reviewed_result['id']) & (
                    C('approval_user_id') == persion_id) & (C('step_no') == jlb_record['step_no'])).project({'_id': 0})
                process_data = self.query(
                    _filter_process, 'PT_Approval_Process')
                if len(process_data) > 0 and 'subsidy_res' in reviewed_result.keys() and 'opinion' in reviewed_result.keys():
                    # 获取审批结果
                    subsidy_result = reviewed_result['subsidy_res']
                    process = process_data[0]
                    process['opinion'] = []
                    process['opinion'].append(reviewed_result['opinion'])
                    if subsidy_result == '通过':
                        process['status'] = '通过'
                        # 判断是否最后一步，最后一步则完结业务单据状态且step_no改为空,不是最后一步则把step_no改为下一步
                        _filter_process_length = MongoBillFilter()
                        _filter_process_length.match_bill(
                            (C('business_id') == reviewed_result['id'])).project({'_id': 0})
                        process_data_length = len(self.query(
                            _filter_process_length, 'PT_Approval_Process'))
                        if jlb_record['step_no'] > 0 and process_data_length == jlb_record['step_no']:
                            # 最后一步
                            jlb_record['status'] = '通过'
                            jlb_record['step_no'] = -1
                            # 往user表里新增一条服务商信息
                            user_insert_info = {"name": jlb_record['name'], "admin_area_id": jlb_record['admin_area_id'], "personnel_type": "2",
                                                "organization_info": {"telephone": jlb_record['telephone'], "introduction": jlb_record['introduction'], "picture_list": jlb_record['picture_list'],
                                                                      "organization_nature": jlb_record['organization_nature'], "lon": jlb_record['lon'], "lat": jlb_record['lat'],
                                                                      "personnel_category": "服务商", "super_org_id": jlb_record['super_org_id'], "legal_person": jlb_record['legal_person'],
                                                                      "business_license_url": jlb_record['business_license_url'], "address": jlb_record['address'],
                                                                      }
                                                }
                            organization_inset_info = get_info(
                                user_insert_info, self.session)
                            bill_id = self.bill_manage_server.add_bill(
                                OperationType.add.value, TypeId.servicePersonal.value, organization_inset_info, ['PT_User'])
                            print("新增服务商的信息>>>>>>>>>>>>", bill_id)
                            # 查询当前用户的信息
                            _filter = MongoBillFilter()
                            _filter.match_bill((C('id') == persion_id))\
                                .project({'_id': 0})
                            user_info_res = self.query(_filter, 'PT_User')
                            user_info = user_info_res[0]
                            # 再把新增的服务商id绑到当前用户的组织机构id
                            user_info['organization_id'] = organization_inset_info['id']
                            bill_id = self.bill_manage_server.add_bill(
                                OperationType.update.value, TypeId.servicePersonal.value, user_info, ['PT_User'])
                            # 查询服务商超级管理员角色id
                            _filter = MongoBillFilter()
                            _filter.match_bill((C('name') == "超级管理员")
                                               & (C('role_type') == "服务商"))\
                                .project({'_id': 0})
                            role_res = self.query(_filter, 'PT_Role')
                            print(role_res)
                            role_id = role_res[0]['id']
                            # 将当前用户的角色设置为服务商超级管理员
                            role_insert_info = {"principal_account_id": persion_id,
                                                "role_of_account_id": organization_inset_info['id'], "role_id": role_id}
                            bill_id = self.bill_manage_server.add_bill(
                                OperationType.add.value, TypeId.servicePersonal.value, role_insert_info, ['PT_Set_Role'])
                            if bill_id:
                                res = 'Success'
                        elif jlb_record['step_no'] > 0 and process_data_length > jlb_record['step_no']:
                            # 非最后一步
                            jlb_record['status'] = '审批中'
                            jlb_record['step_no'] = jlb_record['step_no'] + 1
                        else:
                            return '无法重复审批'
                    if subsidy_result == '不通过':
                        process['status'] = '不通过'
                        # 把业务单据的状态改为不通过
                        jlb_record['status'] = '不通过'
                    # 修改业务表和过程表
                    data = [jlb_record, process]
                    bill_id = self.bill_manage_server.add_bill(OperationType.update.value, TypeId.servicePersonal.value, data, [
                        'PT_Service_Provider_Register', 'PT_Approval_Process'])
                    if bill_id:
                        res = 'Success'
        return res

    def del_service_provider(self, ids):
        '''删除服务商'''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            for business_id in ids:
                data = find_data(db, 'PT_Service_Provider_Register', {
                    'id': business_id, 'bill_status': Status.bill_valid.value})
                if len(data) > 0:
                    self.bill_manage_server.add_bill(OperationType.delete.value,
                                                     TypeId.serviceProvider.value, data[0], 'PT_Service_Provider_Register')
            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def get_service_type_list(self, condition, page=None, count=None):
        '''查询服务类型列表'''
        keys = ['id', 'is_top', 'name', 'is_show_app', 'parent_id']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.add_fields({
            'create_date': self.ao.date_to_string('$create_date'),
            'modify_date': self.ao.date_to_string('$modify_date')})\
            .match_bill((C('id') == values['id']) & (C('name') == values['name']) & (C('is_show_app') == values['is_show_app']) & (C('parent_id') == values['parent_id']))\
            .sort({'show_num': 1})\
            .project({'_id': 0})
        if 'is_top' in condition.keys():
            _filter.match((C('parent_id') == '') | (C('parent_id') == None))
        res = self.page_query(
            _filter, "PT_Service_Type", page, count)
        return res

    def get_service_type_list_tree(self, condition, page=None, count=None):
        '''查询服务类型树形结构列表'''
        _filter = MongoBillFilter()
        _filter.match_bill((C('parent_id') == '') | (C('parent_id') == None))\
            .add_fields({
                'label': '$name',
                'value': '$name',
                'children': []
            })\
            .project({'_id': 0, 'id': 1, 'label': 1, 'value': 1, 'children': 1})
        res = self.page_query(_filter, 'PT_Service_Type', page, count)
        result = []
        if len(res['result']) > 0:
            for data in res['result']:
                new_res = self.query_child(data['id'], condition)
                r_data = self.xuhuan(new_res, data, condition)
                result.append(r_data)

        res['result'] = result
        return res

    def xuhuan(self, new_res, return_data, condition):
        if len(new_res) > 0:
            return_data['children'] = new_res
            for data in new_res:
                child_data = self.query_child(data['id'], condition)
                self.xuhuan(child_data, data, condition)
        return return_data

    def query_child(self, parent_id, condition):
        keys = ['']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('parent_id') == parent_id))\
            .add_fields({
                'label': '$name',
                'value': '$id',
                'children': []
            })\
            .project({'_id': 0, 'id': 1, 'label': 1, 'value': 1, 'children': 1})
        res = self.query(
            _filter, "PT_Service_Type")
        return res

    def update_service_type(self, serviceType):
        '''新增/修改类型'''
        res = 'Fail'
        data_info = get_info({**serviceType}, self.session)

        def process_func(db):
            nonlocal res
            if 'id' in serviceType.keys():
                flag = OperationType.update.value
            else:
                flag = OperationType.add.value
            bill_id = self.bill_manage_server.add_bill(flag,
                                                       TypeId.serviceType.value, data_info, 'PT_Service_Type')
            if bill_id:
                res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def del_service_type(self, ids):
        '''删除服务类型'''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            for business_id in ids:
                data = find_data(db, 'PT_Service_Type', {
                    'id': business_id, 'bill_status': Status.bill_valid.value})
                if len(data) > 0:
                    self.bill_manage_server.add_bill(OperationType.delete.value,
                                                     TypeId.serviceType.value, data[0], 'PT_Service_Type')
            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def recovery_service_type(self, data_id):
        '''恢复上一版本数据'''
        return self.bill_manage_server.recovery_previous_version(data_id, 'PT_Service_Type')

    def get_service_item_list(self, order_ids, condition, page=None, count=None):
        '''查询服务项目列表'''
        keys = ['id', 'service_type_id']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill(C('organization_id').inner(order_ids))\
            .lookup_bill('PT_User', 'service_provider_id', 'id', 'user')\
            .lookup_bill('PT_Service_Type', 'service_type_id', 'id', 'type')\
            .add_fields({'service_type_name': '$type.name',
                         'service_provider_name': '$user.name',
                         'create_date': self.ao.date_to_string('$create_date'),
                         'modify_date': self.ao.date_to_string('$modify_date')})\
            .match_bill((C('id') == values['id']) & (C('service_type_id').inner(values['service_type_id'])))\
            .project({'_id': 0, 'user._id': 0, 'type._id': 0})
        res = self.page_query(
            _filter, 'PT_Service_Item', page, count)
        return res

    def update_service_item(self, serviceItem):
        '''新增/修改服务项目 '''
        res = 'Fail'
        data_info = get_info({**serviceItem}, self.session)

        def process_func(db):
            nonlocal res
            if 'id' in serviceItem.keys():
                flag = OperationType.update.value
            else:
                flag = OperationType.add.value
            bill_id = self.bill_manage_server.add_bill(flag,
                                                       TypeId.serviceItem.value, data_info, 'PT_Service_Item')
            if bill_id:
                res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def del_service_item(self, ids):
        ''' 删除服务项目 '''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            for item_id in ids:
                data = find_data(db, 'PT_Service_Item', {
                    'id': item_id, 'bill_status': Status.bill_valid.value})
                if len(data) > 0:
                    self.bill_manage_server.add_bill(OperationType.delete.value,
                                                     TypeId.serviceItem.value, data[0], 'PT_Service_Item')
            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def recovery_service_item(self, data_id):
        '''恢复上一版本数据'''
        return self.bill_manage_server.recovery_previous_version(data_id, 'PT_Service_Item')

    def service_evaluate(self, serviceEvaluate):
        ''' 服务记录评价 serviceEvaluate：{id:'',evaluate:{}}'''
        res = 'Fail'

        def process_func(db):
            # 先查服务记录信息，再增加评价内容
            nonlocal res
            # 评价人Id取当前操作用户id
            user_id = get_current_user_id(self.session)
            evaluate = serviceEvaluate['evaluate']
            evaluate['evaluator_id'] = user_id
            record_mes = find_data(db, 'PT_Service_Record', {
                                   'id': serviceEvaluate['id']})
            if len(record_mes) > 0:
                if 'evaluate_list' in record_mes[0]:
                    record_mes[0]['evaluate_list'] = record_mes[0]['evaluate_list'] + evaluate
                else:
                    record_mes[0]['evaluate_list'] = evaluate
                bill_id = self.bill_manage_server.add_bill(OperationType.update.value,
                                                           TypeId.serviceItemEvaluate.value, record_mes[0], 'PT_Service_Record')
                if bill_id:
                    res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def get_service_order_list(self, order_ids, condition, page=None, count=None):
        '''查询服务订单列表'''
        keys = ['id', 'purchaser_name', 'purchaser_id_card', 'service_provider_id', 'purchaser_id', 'status',
                'order_date', 'service_date', 'pay_date', 'order_state', 'origin_product', 'need_fp', 'transation_code']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.lookup('PT_User', 'service_provider_id', 'id', 'serviceProvider')\
            .inner_join_bill('PT_User', 'purchaser_id', 'id', 'purchaser')\
            .match_bill((C('purchaser.name').like(values['purchaser_name']))
                        & (C('purchaser.id_card').like(values['purchaser_id_card']))
                        )\
            .add_fields({
                'service_provider': '$serviceProvider.name',
                        'purchaser': '$purchaser.name',
                        'purchaser_id_card': '$purchaser.id_card',
                        'purchaser_address': '$purchaser.personnel_info.address',
                        'create_date': self.ao.date_to_string('$create_date'),
                        'modify_date': self.ao.date_to_string('$modify_date')})\
            .match_bill((C('id') == values['id']) & (C('status') == values['status']) & (C('organization_id').inner(order_ids))
                        & (C('purchaser_id') == values['purchaser_id'])
                        & (C('service_provider_id').inner(values['service_provider_id']))
                        & (C('order_code').like(values['transation_code']))
                        )\
            .sort({'order_date': -1})\
            .project({'_id': 0,
                      'serviceProvider._id': 0,
                      'purchaser._id': 0, })
        if condition.get('order_date'):
            before_date = condition['order_date'][0]
            after_date = condition['order_date'][1]
            _filter.match_bill(
                (C('order_date') > as_date(before_date))
                & (C('order_date') < as_date(after_date))
            )

        if condition.get('service_date'):
            before_date = condition['service_date'][0]
            after_date = condition['service_date'][1]
            _filter.match_bill(
                (C('service_date') > as_date(before_date))
                & (C('service_date') < as_date(after_date))
            )

        if condition.get('pay_date'):
            before_date = condition['pay_date'][0]
            after_date = condition['pay_date'][1]
            _filter.match_bill(
                (C('pay_date') > as_date(before_date))
                & (C('pay_date') < as_date(after_date))
            )
        res = self.page_query(
            _filter, 'PT_Service_Order', page, count)
        # 拼接订单内容
        if res['result']:
            for result in res['result']:
                if result.get('service_item'):
                    order_list = []
                    # number = 0
                    for item in result.get('service_item'):
                        # number += 1
                        _filter_item = MongoBillFilter()
                        _filter_item.match_bill(C('id') == item.get(
                            'service_item')).project({'_id': 0})
                        res_item = self.query(_filter_item, 'PT_Service_Item')
                        if res_item:
                            item['service_name'] = res_item[0]['name']
                        else:
                            item['service_name'] = ''
                        if item.get('service_options'):
                            option_list = []
                            for option in item.get('service_options'):
                                if option.get('name') and option.get('value'):
                                    option_content = ''.join(
                                        (option.get('name'), '(', str(option.get('value')), ')'))
                                    option_list.append(option_content)
                                else:
                                    option_list.append(' ')
                            if not item.get('count'):
                                item['count'] = 1
                            item_content = ''.join(
                                (item['service_name'], '-', ('-'.join(option_list))))+'*'+str(item.get('count'))
                            order_list.append(item_content)
                    # print(order_list)
                    order_list = '、'.join(order_list)
                    result['order_list'] = order_list
        return res

    def update_service_order(self, service_order):
        ''' 新增/修改服务订单'''
        res = 'Fail'
        if service_order.get('order_date'):
            service_order['order_date'] = as_date(service_order['order_date'])
        if service_order.get('service_date'):
            service_order['service_date'] = as_date(
                service_order['service_date'])
        if service_order.get('pay_date'):
            service_order['pay_date'] = as_date(service_order['pay_date'])

        def process_func(db):
            nonlocal res
            if 'id' in service_order.keys():
                bill_id = self.bill_manage_server.add_bill(OperationType.update.value,
                                                           TypeId.serviceOrder.value, service_order, 'PT_Service_Order')
                if bill_id:
                    res = 'Success'
            else:
                service_order['order_code'] = get_serial_number(
                    db, SerialNumberType.order.value)
                bill_id = self.bill_manage_server.add_bill(OperationType.add.value,
                                                           TypeId.serviceOrder.value, service_order, 'PT_Service_Order')
                if bill_id:
                    res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def service_book(self, serviceItems, remark=''):
        '''服务预定(根据选择的服务项目新增一个服务订单)'''
        res = 'Fail'
        order_detail = []
        order_fee = 0
        for item in serviceItems:
            order_detail.append(
                {"id": item['id'], "item_content": item['item_content'], "remark": item['remark']})
            order_fee = order_fee + float(item['item_fee'])

        def process_func(db):
            nonlocal res
            nonlocal order_detail
            nonlocal order_fee
            order = Order(get_current_user_id(
                self.session), serviceItems[0]['service_provider_id'], order_fee, order_detail, remark)
            order_info = get_info(order.to_dict(), self.session)
            result = insert_data(db, 'PT_Service_Order', order_info)
            if result:
                res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res
    '''入参是服务订单明细对象'''

    def service_consult(self, order_id):
        '''服务协商(传入服务订单id，新增交易信息数据，并与订单绑定)'''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            # 查询服务订单信息
            order_data = find_data(db, 'PT_Service_Order', {
                'id': order_id})
            if len(order_data) > 0:
                item_content = ""
                for detail in order_data[0]['detail']:
                    item_content = item_content + detail['item_content'] + " "
                print(item_content, 'item_content')
                # 新增交易信息
                transaction = {'transaction_code': get_code(), 'party_a': order_data[0]['purchaser_id'],
                               'party_b': order_data[0]['service_provider_id'], 'transaction_date': get_cur_time().strftime("%Y-%m-%d %H:%M:%S"),
                               'transaction_money': order_data[0]['order_fee'], 'abstract': item_content,
                               'transaction_state': '进行中', 'transaction_content': item_content}
                print(transaction, 'transaction')
                transation_id = self.transaction_service.add_transaction(
                    transaction)
                # 交易id绑定服务订单
                order_data[0]['transation_id'] = transation_id
                order_data[0]['status'] = Status.bill_valid.value
                result = update_data(db, 'PT_Service_Order',
                                     order_data[0], {'id': order_id})
                if result:
                    res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def change_service_order_status(self, order_id, new_status):
        '''修改服务订单状态'''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            data = {}
            data['status'] = new_status
            result = update_data(db, 'PT_Service_Order',
                                 data, {'id': order_id})
            if result:
                res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def service_pay(self, serviceBook):
        '''服务支付'''
        res = 'Fail'
        # 支付功能待定
        return res

    def get_service_evaluate_list(self, condition, page=None, count=None):
        '''查询服务评价列表'''
        keys = ['id', 'service_provider_id']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.lookup('PT_User', 'evaluator_id', 'id', 'evaluator')\
            .lookup('PT_Service_Item', 'service_item_id', 'id', 'serviceItem')\
            .add_fields({
                'evaluator': '$evaluator.name',
                        'create_date': self.ao.date_to_string('$create_date'),
                        'modify_date': self.ao.date_to_string('$modify_date')})\
            .match((C('bill_status') == Status.bill_valid.value) & (C('id') == values['id']) & (C('serviceItem.service_provider_id').inner(values['service_provider_id'])))\
            .project({'_id': 0,
                      'evaluator._id': 0,
                      'serviceItem._id': 0})
        res = self.page_query(
            _filter, "PT_Service_Item_Evaluate", page, count)
        return res

    # def add_service_record(self,order_ids,process_name=None,cal_values=None,begin_date=None,end_date=None):
    #     '''新增服务记录（根据服务订单生成服务记录）'''
    #     result = False
    #     print('订单id',order_ids)
    #     if process_name:
    #         for order_id in order_ids:
    #             recode_param = self.accommodation_process.get_item_info(process_name, order_id, cal_values)
    #             _filters = MongoBillFilter()
    #             _filters.lookup_bill('PT_Service_Order', 'order_id', 'id', 'order')\
    #                     .match_bill((
    #                                 ((C('start_date') <= begin_date)
    #                                 & (C('end_date') >= end_date))
    #                                 | ((C('start_date') >= begin_date) & (C('end_date') <= end_date))
    #                                 | ((C('start_date') >= begin_date) & (C('start_date') <= end_date))
    #                                 | ((C('end_date') >= begin_date) & (C('end_date') <= end_date))
    #                             ) & (C('order_id') == order_id) & (C('service_product_id') == recode_param['service_product_id']))\
    #                     .project({'_id': 0})
    #             recode = self.query(_filters, 'PT_Service_Record')
    #             if not len(recode):
    #                 order_record = OrderRecord(
    #                     order_id, recode_param['service_product_id'], '', '',recode_param['option_list'],begin_date, end_date)
    #                 data_info = get_info(order_record.to_dict())
    #                 result = self.bill_manage_server.add_bill(
    #                     OperationType.add.value, TypeId.serviceRecord.value, data_info, 'PT_Service_Record')
    #     return operation_result(result)

    def add_service_record(self, order_id, product_id, is_virtual, other={}, is_update=False):
        '''新增服务记录（根据服务订单生成服务记录）'''
        # 判断服务记录是否存在
        self.has_exit_recode(order_id, product_id, is_update, other=other)
        recode = {'order_id': order_id,
                  'service_product_id': product_id, 'service_option': []}
        if is_update:
            recode.update(id=is_update)
            print('我进来了，这是编辑')
        recode['is_virtual'] = '1' if is_virtual else '0'
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == order_id)) \
            .unwind('detail') \
            .match_bill(C('detail.product_id') == product_id)\
            .project({'_id': 0})
        res = self.query(_filter, 'PT_Service_Order')
        if len(res):
            item = res[0]['detail']
            # print('item:<<<<<',item)
            option = item['service_option']
            if type(item['valuation_formula']) == list:
                method = item['valuation_formula'][0]['formula']
            elif type(item['valuation_formula']) == str:
                method = item['valuation_formula']
            # print('我在这里',res[0]['is_paying_first'])
            # 后付费
            if res[0]['is_paying_first'] == '1':
                other['service_option'] = recode['service_option'] + \
                    other['service_option']

                recode['valuation_amount'] = round(self.execute_python(
                    method, other['service_option']), 2)  # 计价金额

                recode['status'] = RecordStatus.service_before.value
                recode['service_option'] = other['service_option']
            else:  # 先付费
                # 暂时改成不管虚拟服务记录这种情况，对于虚拟服务记录，其实与服务订单的金额一致的
                for x in option:
                    recode['service_option'].append(x)
                recode['valuation_amount'] = round(self.execute_python(
                    method, recode['service_option']), 2)  # 计价金额
                # if is_virtual == '1':  # 虚拟记录,只保存服务前选项
                #     for x in option:
                #         # print(x,'x>>>>')
                #         if x['option_type'] == 'service_before':
                #             recode['service_option'].append(x)

                #     recode['valuation_amount'] = round(self.execute_python(method, recode['service_option']),2)  # 计价金额
                # else:  #非虚拟记录，不生成金额，选项为服务后选项
                #     for x in option:
                #         if x['option_type'] == 'service_after':
                #             recode['service_option'].append(x)
                #     recode['valuation_amount'] = 0
        else:
            raise JsonRpc2Error('-35007', '该订单不存在')

        recode = dict(recode, **other)
        return get_info(recode, self.session)

    def has_exit_recode(self, order_id, product_id, is_update, other={}):
        res = []
        if 'start_date' in other.keys() and 'end_date' in other.keys():
            start_date = other['start_date']
            end_date = other['end_date']
            _filter = MongoBillFilter()
            if is_update:  # 编辑，过滤自身
                _filter.match_bill(C('id') != is_update)
                # print(_filter.filter_objects)
            _filter.match_bill(
                (C('order_id') == order_id)
                & (C('service_product_id') == product_id)
                & (((C('start_date') >= start_date) & (end_date >= C('start_date')))
                   | ((C('start_date') < start_date) & (C('end_date') > start_date)))
            )\
                .project({'_id': 0})
            res = self.query(_filter, 'PT_Service_Record')
        if len(res):
            raise JsonRpc2Error('-35006', '服务记录已存在')

        # result = False
        # print('订单id',order_ids)
        # if process_name:
        #     for order_id in order_ids:
            # recode_param = self.accommodation_process.get_item_info(process_name, order_id, cal_values)
        #         _filters = MongoBillFilter()
        #         _filters.lookup_bill('PT_Service_Order', 'order_id', 'id', 'order')\
        #                 .match_bill((
        #                             ((C('start_date') <= begin_date)
        #                             & (C('end_date') >= end_date))
        #                             | ((C('start_date') >= begin_date) & (C('end_date') <= end_date))
        #                             | ((C('start_date') >= begin_date) & (C('start_date') <= end_date))
        #                             | ((C('end_date') >= begin_date) & (C('end_date') <= end_date))
        #                         ) & (C('order_id') == order_id) & (C('service_product_id') == recode_param['service_product_id']))\
        #                 .project({'_id': 0})
        #         recode = self.query(_filters, 'PT_Service_Record')
        #         if not len(recode):
        #             order_record = OrderRecord(
        #                 order_id, recode_param['service_product_id'], '', '',recode_param['option_list'],begin_date, end_date)
        #             data_info = get_info(order_record.to_dict())
        #             result = self.bill_manage_server.add_bill(
        #                 OperationType.add.value, TypeId.serviceRecord.value, data_info, 'PT_Service_Record')
        # return operation_result(result)

        # res = 'Fail'
        # _filter = MongoBillFilter()
        # _filter.match_bill((C('id').inner(order_ids)))\
        #        .project({'_id': 0,'item._id': 0})
        # # .add_fields({
        # #             'create_date': self.ao.date_to_string('$create_date'),
        # #             'modify_date': self.ao.date_to_string('$modify_date')})\
        # order_data = self.query(
        #     _filter, "PT_Service_Order")

    #     def process_func(db):
    #         nonlocal res
    #         nonlocal order_data
    #         user_id = get_person_id(db, self.session)
    #         if len(order_data) > 0:
    #             for order in order_data:
    #                 # 遍历服务产品
    #                 for detail in order['service_item']:
    #                     begin_date = None
    #                     end_date = None
    #                     service_product_id = detail['service_item']
    #                     option_list = detail['service_options']
    #                     # 服务内容取项目的合同条款
    #                     content = detail['contract_clauses']
    #                     # 取项目中的周期性类型字段
    #                     # if 'periodicity' in detail:
    #                     #     periodicity_data = find_data(db, 'PT_Periodicity_Date', {
    #                     #         'id': detail['periodicity']})
    #                     #     if len(periodicity_data) > 0:
    #                     #         days = periodicity_data[0]['days']
    #                     #         date = get_date_slot(days, choice_date)
    #                     #         # begin_date = as_date(date['begin_date'])
    #                     #         begin_date = date['begin_date'].strftime(
    #                     #             "%Y-%m-%d %H:%M:%S")
    #                     #         end_date = date['end_date'].strftime(
    #                     #             "%Y-%m-%d %H:%M:%S")
    #                     #         # end_date = as_date(date['end_date'])
    #                     # else:
    #                     begin_date = as_date(
    #                         get_cur_time().strftime("%Y-%m-%d %H:%M:%S"))
    #                     end_date = as_date(
    #                         get_cur_time().strftime("%Y-%m-%d %H:%M:%S"))
    #                     _filters = MongoBillFilter()
    #                     _filters.lookup_bill('PT_Service_Order', 'order_id', 'id', 'order')\
    #                         .add_fields({
    #                             'purchaser_id': '$order.purchaser_id',
    #                         })\
    #                         .match_bill((
    #                             ((C('start_date') <= begin_date)
    #                              & (C('end_date') >= end_date))
    #                             | ((C('start_date') >= begin_date) & (C('end_date') <= end_date))
    #                             | ((C('start_date') >= begin_date) & (C('start_date') <= end_date))
    #                             | ((C('end_date') >= begin_date) & (C('end_date') <= end_date))
    #                         ) & (C('purchaser_id') == order_data[0]['purchaser_id']) & (C('order_id') == order['id']) & (C('item_id') == service_product_id))\
    #                         .project({'_id': 0})
    #                     record = self.query(_filters, "PT_Service_Record")
    #                     if len(record) == 0:
    #                         # 如果存在数据，则证明已存在与该时间段重叠的数据
    #                         order_record = OrderRecord(
    #                             order['id'], service_product_id, user_id, content,option_list,begin_date, end_date)
    #                         data_info = get_info(order_record.to_dict())
    #                         result = self.bill_manage_server.add_bill(
    #                             OperationType.add.value, TypeId.serviceRecord.value, data_info, 'PT_Service_Record')
    #                         if result:
    #                             res = 'Success'
    #     process_db(self.db_addr, self.db_port, self.db_name, process_func)
    #     return res

    def add_service_record_option(self, record_id, options):
        '''记录服务记录项目值接口：记录选项值，然后根据公式计算出金额。入参options：[{'name','value'}]'''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            nonlocal options
            record_mes = find_data(db, 'PT_Service_Record', {
                'id': record_id, 'bill_status': Status.bill_valid.value})
            if len(record_mes) > 0:
                if 'service_option' in record_mes[0]:
                    record_mes[0]['service_option'] = record_mes[0]['service_option'] + options
                else:
                    record_mes[0]['service_option'] = options
                # 获取产品id
                product_id = record_mes[0]['service_product_id']
                # 查找订单获取计价改订单下某个产品的定价公式
                order_mes = find_data(db, 'PT_Service_Order', {
                                      'id': record_mes[0]['order_id'], 'bill_status': Status.bill_valid.value})
                # 获取服务记录的产品id
                if len(order_mes) > 0:
                    item_detail = order_mes[0]['service_item']
                    if len(item_detail) > 0:
                        for item in item_detail:
                            options = options + item['service_option']
                    # 根据公式计算金额 TODO公式方法
                    valuation_formula = item_detail[0]['valuation_formula']
                    # 公式中的参数字段替换为值
                    valuation_amount = round(self.execute_python(
                        valuation_formula, options), 2)
                    record_mes[0]['valuation_amount'] = valuation_amount
                result = self.bill_manage_server.add_bill(OperationType.update.value,
                                                          TypeId.serviceRecord.value, record_mes[0], 'PT_Service_Record')
                if result:
                    res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def execute_python(self, valuation_formula, options):
        ''' 执行Python字符串方法'''
        names = locals()
        total = 0
        for option in options:
            if option.get('option_name'):
                names[str(option.get('option_name'))
                      ] = option.get('option_value')
            elif option.get('name'):
                names[str(option.get('name'))] = option.get('option_value')
        try:
            # print(valuation_formula)
            # print(names)
            total = eval(valuation_formula, names)
        except:
            total = 0
        return total

    def update_services_ledger(self, record_ids):
        ''' 生成台账数据'''
        res = 'Fail'
        # 查询记录，根据订单中的同一个人，合并生成台账记录
        _filter = MongoFilter()
        _filter.lookup('PT_Service_Order', 'order_id', 'id', 'order')\
            .add_fields({
                'purchaser_id': '$order.purchaser_id',
                'create_date': self.ao.date_to_string('$create_date'),
                'modify_date': self.ao.date_to_string('$modify_date')})\
            .match((C('bill_status') == Status.bill_valid.value))\
            .project({'_id': 0,
                      'order._id': 0})
        record_data = self.query(_filter, "PT_Service_Record")

        def process_func(db):
            nonlocal res
            nonlocal record_data
            # if len(record_data) > 0:
            # for record in record_data:

            # ledger = Ledger()
            # data_info = get_info(order_record.to_dict())
            # result = self.bill_manage_server.add_bill(
            #     OperationType.add.value, TypeId.serviceLedger.value, data_info, 'PT_Service_Ledger')
            # if result:
            #     res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def get_service_ledger_list(self, condition, page=None, count=None):
        '''查询台账列表'''
        keys = ['id']
        values = self.get_value(condition, keys)
        _filter = MongoFilter()
        _filter.lookup('PT_User', 'user_id', 'id', 'user')\
            .add_fields({
                'user_name': '$user.name',
                'create_date': self.ao.date_to_string('$create_date'),
                'modify_date': self.ao.date_to_string('$modify_date')})\
            .match((C('bill_status') == Status.bill_valid.value) & (C('id') == values['id']))\
            .project({'_id': 0,
                      'user._id': 0})
        res = self.page_query(
            _filter, "PT_Service_Ledger", page, count)
        return res

    def update_service_settlement(self, service_settlement):
        ''' 服务结算'''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            if 'id' in service_settlement.keys():
                bill_id = self.bill_manage_server.add_bill(OperationType.update.value,
                                                           TypeId.serviceSettlement.value, service_settlement, 'PT_Service_Record')
                if bill_id:
                    res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    # def update_service_provider_record(self, status, id):
    #     ''' 服务商申请审核'''
    #     res = 'Fail'
    #     _filter = MongoBillFilter()
    #     _filter.match_bill(C('service_provider_id') == id)\
    #         .project({'_id': 0, })
    #     res = self.page_query(
    #         _filter, "PT_Service_Provider_Register", 1, 1)
    #     res['result'][0]['status'] = status
    #     entity=res['result'][0]
    #     print(res['result'])
    #     print(id)

    #     def process_func(db):
    #         nonlocal entity
    #         nonlocal res
    #         bill_id = self.bill_manage_server.add_bill(OperationType.update.value,
    #                                                     TypeId.serviceSettlement.value, entity, 'PT_Service_Provider_Register')
    #         if bill_id:
    #             res = 'Success'
    #     process_db(self.db_addr, self.db_port, self.db_name, process_func)

    #     return res

    def add_service_order_comment(self, orderComments):
        """ 新增服务订单评论 orderComment： [{order_id, product_id, service_attitude,service_quality,opinion_remarks}] """
        res = 'Fail'
        for orderComment in orderComments:
            data = ServiceOrderCommentObject(
                get_current_user_id(self.session), orderComment['order_id'], orderComment['product_id'], orderComment['service_attitude'], orderComment['service_quality'], orderComment['opinion_remarks']).to_dict()
            data_info = get_info(data, self.session)
            bill_id = self.bill_manage_server.add_bill(OperationType.add.value,
                                                       TypeId.orderComment.value, data_info, 'PT_Service_Order_Comment')
            if bill_id:
                res = "Success"
        return res
